package modules.gameCommunication;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.TreeMap;

import objects.Account;

import common.Constants;
import common.GameServer;

import modules.configuration.GameConf;

public class GameServerThread implements Runnable {

    private static boolean _running = false;
    private static GameServerThread _self;
    private static ArrayList<DataCenter> _clients = new ArrayList<DataCenter>();
    private static TreeMap<Long, Account> _waitingAccounts = new TreeMap<Long, Account>();

    public GameServerThread() {
        if (_self != null) {
            return;
        }
        _self = this;

        //Launch ServerSocket
        Thread mainThread = new Thread(this);
        mainThread.setDaemon(true);
        mainThread.start();
        GameServer.updateState(Constants.SERVER_STATE_ONLINE);
    }

    @Override
    public void run() {
        try {
            ServerSocket ss = new ServerSocket(GameConf._gamePort);
            _running = true;
            GameServer.writeLine("Ok!");
            while (_running)//block on ss.accept()
            {
                try {
                    _clients.add(new DataCenter(ss.accept()));
                } catch (Exception e) {
                    GameServer.writeLine("Error: " + e.getMessage());
                    e.printStackTrace();
                    GameServer.writeLine("Server is now exiting...");
                    System.exit(1);
                }
            }
        } catch (IOException e) {
            GameServer.writeLine("Error: Game-server socket cannot be open");
            GameServer.writeLine("Maybe the port is not available...");
            GameServer.writeLine("Server is now exiting...");
            System.exit(1);
            return;
        }
    }

    public void stop() {
        _running = false;
    }

    public static boolean isRunning() {
        return _running;
    }

    public static void addWaitingAccount(Account acc) {
        _waitingAccounts.put(acc.getGuid(), acc);
        GameServer.writeLine("Account " + acc.getGuid() + " registered in waiting list");
    }

    public static void delWaitingAccount(long guid) {
        _waitingAccounts.remove(guid);
    }

    public static Account getWaitingAccount(long guid) {
        return _waitingAccounts.get(guid);
    }

    public static ArrayList<DataCenter> getClients() {
        return _clients;
    }
}
